//
//  MACookManageViewController.m
//  meiang_edu
//
//  Created by 栋 on 2019/1/15.
//  Copyright © 2019年 com.meiang.meiang_edu. All rights reserved.
//

#import "MACookManageViewController.h"
#import "FSCalendar.h"
#import "MACookManageCell.h"
#import <EventKit/EventKit.h>

@interface MACookManageViewController ()<UITableViewDataSource,UITableViewDelegate,FSCalendarDelegate,FSCalendarDataSource,UIGestureRecognizerDelegate>

@property (weak, nonatomic) IBOutlet UIView *calendarView;
@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (nonatomic ,strong) NSMutableArray *dataSource;
@property (nonatomic ,strong) FSCalendar *calendar;
@property (nonatomic ,strong) UIPanGestureRecognizer *scopeGesture;
@property (strong, nonatomic) NSDateFormatter *dateFormatter;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *layoutCalendarContentHeight;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *layoutCalendarContentTop;

@property (strong, nonatomic) NSCalendar *chineseCalendar;
@property (strong, nonatomic) NSArray<NSString *> *lunarChars;
@property (strong, nonatomic) NSArray<EKEvent *> *events;
@end

@implementation MACookManageViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    [self setUpTableView];
    self.dateFormatter = [[NSDateFormatter alloc] init];
    self.dateFormatter.dateFormat = @"yyyy/MM/dd";
    
    self.chineseCalendar = [NSCalendar calendarWithIdentifier:NSCalendarIdentifierChinese];
    
//    NSInteger lunarDay = [self.chineseCalendar component:NSCalendarUnitDay fromDate:date];
    self.lunarChars = @[@"初一",@"初二",@"初三",@"初四",@"初五",@"初六",@"初七",@"初八",@"初九",@"初十",@"十一",@"十二",@"十三",@"十四",@"十五",@"十六",@"十七",@"十八",@"十九",@"二十",@"廿一",@"廿二",@"廿三",@"廿四",@"廿五",@"廿六",@"廿七",@"廿八",@"廿九",@"三十"];
//    NSString *lunarDayString = self.lunarChars[day-1];
    self.chineseCalendar = [NSCalendar calendarWithIdentifier:NSCalendarIdentifierChinese];
    

    self.layoutCalendarContentTop.constant = NavHeight;
    
    UIPanGestureRecognizer *panGesture = [[UIPanGestureRecognizer alloc] initWithTarget:self.calendar action:@selector(handleScopeGesture:)];
    panGesture.delegate = self;
    panGesture.minimumNumberOfTouches = 1;
    panGesture.maximumNumberOfTouches = 2;
    [self.view addGestureRecognizer:panGesture];
    self.scopeGesture = panGesture;

//     While the scope gesture begin, the pan gesture of tableView should cancel.
    [self.tableView.panGestureRecognizer requireGestureRecognizerToFail:panGesture];
    [self.calendar addObserver:self forKeyPath:@"scope" options:NSKeyValueObservingOptionNew|NSKeyValueObservingOptionOld context:nil];
    [self.calendar reloadData];
    [self.view layoutIfNeeded];
    
}

- (void)setUpTableView{
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.estimatedRowHeight = 100;
    self.tableView.rowHeight = UITableViewAutomaticDimension;
    self.tableView.tableFooterView = [UIView new];
    [self.tableView registerNib:[UINib nibWithNibName:@"MACookManageCell" bundle:nil] forCellReuseIdentifier:@"MACookManageCell"];
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(headerRefresh)];
}

- (FSCalendar *)calendar{
    if (!_calendar) {
        _calendar = [[FSCalendar alloc] init];
        [self.calendarView addSubview:_calendar];
        [_calendar mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.left.right.mas_equalTo(0);
            make.height.mas_equalTo(300);
        }];
        _calendar.delegate = self;
        _calendar.dataSource = self;
//        _calendar.appearance.headerMinimumDissolvedAlpha = 0.0;
//        _calendar.appearance.borderSelectionColor = PROJECT_DEFAULT_COLOR;
//        _calendar.appearance.selectionColor = PROJECT_DEFAULT_COLOR;
        [_calendar selectDate:[NSDate date] scrollToDate:YES];
        _calendar.placeholderType = FSCalendarPlaceholderTypeNone;
        _calendar.scope = FSCalendarScopeWeek;
//        _calendar.headerHeight = 0;
        
    }
    return _calendar;
}

- (void)headerRefresh{
    
    NSDictionary * parameters = @{
                                  @"ddate":@"2017-07-10"
                                  };
    [MANetwork GET:[NSString stringWithFormat:@"%@%@",COOK_ONEDAY_LIST,_jigouModel.ID] parameters:parameters autoShowFailAlert:YES showLoading:YES success:^(id response, BOOL success) {
        [self.tableView.mj_header endRefreshing];
        NSLog(@"response = %@",response);
        
    } failure:^(NSError *error) {
        [self.tableView.mj_header endRefreshing];
    }];
  
    
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return 4;//self.dataSource.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    MACookManageCell * cell =[tableView dequeueReusableCellWithIdentifier:@"MACookManageCell" forIndexPath:indexPath];
    
    return cell;
}

#pragma mark - <UIGestureRecognizerDelegate>

// Whether scope gesture should begin
- (BOOL)gestureRecognizerShouldBegin:(UIGestureRecognizer *)gestureRecognizer
{
    BOOL shouldBegin = self.tableView.contentOffset.y <= -self.tableView.contentInset.top;
    if (shouldBegin) {
        CGPoint velocity = [self.scopeGesture velocityInView:self.view];
        switch (self.calendar.scope) {
            case FSCalendarScopeMonth:
                return velocity.y < 0;
            case FSCalendarScopeWeek:
                return velocity.y > 0;
        }
    }
    return shouldBegin;
}

#pragma mark - <FSCalendarDelegate>

//- (void)calendar:(FSCalendar *)calendar boundingRectWillChange:(CGRect)bounds animated:(BOOL)animated
//{
//    //    NSLog(@"%@",(calendar.scope==FSCalendarScopeWeek?@"week":@"month"));
////    _calendarHeightConstraint.constant = CGRectGetHeight(bounds);
//    CGFloat height = CGRectGetHeight(bounds);
//    self.layoutCalendarContentHeight.constant = height;
//    [self.calendar mas_updateConstraints:^(MASConstraintMaker *make) {
//        make.height.mas_equalTo(height);
//    }];
//    [self.view layoutIfNeeded];
//}

- (void)calendar:(FSCalendar *)calendar didSelectDate:(NSDate *)date atMonthPosition:(FSCalendarMonthPosition)monthPosition
{
    NSLog(@"did select date %@",[self.dateFormatter stringFromDate:date]);

    NSMutableArray *selectedDates = [NSMutableArray arrayWithCapacity:calendar.selectedDates.count];
    [calendar.selectedDates enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
        [selectedDates addObject:[self.dateFormatter stringFromDate:obj]];
    }];
    NSLog(@"selected dates is %@",selectedDates);
    if (monthPosition == FSCalendarMonthPositionNext || monthPosition == FSCalendarMonthPositionPrevious) {
        [calendar setCurrentPage:date animated:YES];
    }
}

- (void)calendarCurrentPageDidChange:(FSCalendar *)calendar
{
    NSLog(@"%s %@", __FUNCTION__, [self.dateFormatter stringFromDate:calendar.currentPage]);
}

- (NSString *)calendar:(FSCalendar *)calendar subtitleForDate:(NSDate *)date
{
    EKEvent *event = [self eventsForDate:date].firstObject;
    if (event) {
        return event.title; // 春分、秋分、儿童节、植树节、国庆节、圣诞节...
    }
    NSInteger day = [_chineseCalendar component:NSCalendarUnitDay fromDate:date];
    return _lunarChars[day-1]; // 初一、初二、初三...
}

// 某个日期的所有事件
- (NSArray<EKEvent *> *)eventsForDate:(NSDate *)date
{
    NSArray<EKEvent *> *filteredEvents = [self.events filteredArrayUsingPredicate:[NSPredicate predicateWithBlock:^BOOL(EKEvent * _Nullable evaluatedObject, NSDictionary<NSString *,id> * _Nullable bindings) {
        return [evaluatedObject.occurrenceDate isEqualToDate:date];
    }]];
    return filteredEvents;
}


#pragma mark - KVO

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context
{
//    FSCalendarScope oldScope = [change[NSKeyValueChangeOldKey] unsignedIntegerValue];
//    FSCalendarScope newScope = [change[NSKeyValueChangeNewKey] unsignedIntegerValue];
//    NSLog(@"From %@ to %@",(oldScope==FSCalendarScopeWeek?@"week":@"month"),(newScope==FSCalendarScopeWeek?@"week":@"month"));
}

- (void)dealloc
{
    [self.calendar removeObserver:self forKeyPath:@"scope" context:nil];
    NSLog(@"%s",__FUNCTION__);
}

@end
